<?php
namespace submodule\widgets;

use yii\helpers\Html;

class SubmoduleWidget extends \base\BaseWidget
{
    public $message = '';
	


    public function init(){
		
		
		
	}
	
	public function run()
    {
		//print_r($this->options);
		$path = substr($this->viewPath, 0, 1 ) == '_' ? 'common' : 'submodule';
		$viewFile = "@{$path}/widgets/{$this->viewPath}/views/_form";
        echo $this->render($viewFile, self::widgetField());
		if (isset($this->options['fields'])){
		    $this->jquery_validate($this->options['fields']);
		}
		
    }

	/**
	*
	*
	* 字段增加验证规则
	*/
	public function jquery_validate($fields){
		$validate = '';
        $rules = $messages = [];
		$fieldid = $fields['field'];
		$check_str = '';
		$minlength = isset($fields['setting']['minlength']) ? intval($fields['setting']['minlength']) : '';
		$maxlength = isset($fields['setting']['maxlength']) ? intval($fields['setting']['maxlength']) : '';
		$errortip = isset($fields['setting']['errortip']) ? $fields['setting']['errortip'] : '';
		$primarykey = isset($this->options['primarykey']) ? $this->options['primarykey'] : 'id';
		if ($fields['required'] == 1){
			$rules["required"] = true;
			if ($fields['formtype'] == 'ueditor'){
				$check_str .= "check_ueditor: ue_".$fieldid.', ';
			    //if ($rules) $check_str = ', '.$check_str;
				//$rules["check_ueditor"] = "ue_".$fieldid;
			}
			$rules["messages"]['required'] = $errortip ? $errortip : '必填项';
		}
		
		if (isset($fields['unique']) && $fields['unique'] == 1){
			$pk = '';
			if(isset($this->options['attributes'][$primarykey]) && $this->options['attributes'][$primarykey]){
				$pk = $this->options['attributes'][$primarykey];
			}
			$url = \Yii::$app->urlManager->createUrl(['/submodel/check-unique', 'modelid'=>$fields['modelid'], 'field'=>$fieldid, 'pk'=>$pk]);
			$rules["remote"] = [
				'url'=> $url,
				'type'=> "get",
				'dataType'=> "json",
				'data'=> [
					'value'=> '{{value}}',
				]
			];
			$rules["messages"]['remote'] = $errortip;
		}
		if ($minlength){
			$rules["check_rangelength"] = [$minlength, $maxlength];
			$rules["messages"]['check_rangelength'] = $errortip;
		}
		if (isset($fields['setting']['pattern']) && $fields['setting']['pattern']){
			 $check_str = "check_pattern: {$fields['setting']['pattern']}, ";
			 $rules["messages"]['check_pattern'] = $errortip;
		}
		if ($rules || $check_str){
			$check_str = !$rules ? rtrim(', ', $check_str) : $check_str;
			//$rules["messages"] = $errortip;
            $rules = json_encode($rules, JSON_UNESCAPED_UNICODE);
			$rules =  '{'.$check_str . ltrim($rules, '{');
			$rules = str_replace('"{{value}}"', '
			    function() {
					return $("#'.$fieldid.'").val();
				}
			', $rules);
		    $validate = "\$(\"#$fieldid\").rules(\"add\", $rules);".PHP_EOL;
		}
		if (isset($fields['setting']['validate'])) foreach($fields['setting']['validate'] as $v){
			$validate .= $v.PHP_EOL;
		}
		echo PHP_EOL.'<script>$(function(){'.$validate.'});</script>'.PHP_EOL;
	}

}